import { useCallback, useEffect, useMemo, useRef, useState } from 'react';

import { msgError } from '@/utils/msg';
import {
  formatDateYYMMDD,
  getCpasPrimaryColor,
  getGridDefaultPageProps,
  replaceInvalidFileName,
} from '@/utils/pub';
import { LoadPanel, SelectBox } from 'devextreme-react';
import Button from 'devextreme-react/button';
import { Item, MasterDetail, Paging, Toolbar } from 'devextreme-react/data-grid';
import { LoadOptions } from 'devextreme/data';
import CustomStore from 'devextreme/data/custom_store';
import { useModel } from 'umi';
import { CpasIcon, DevGrid } from '~/public/cpas-ui';
import './component/index.less';
import {
  getExportGridDataSource,
  getSampleTypeColumns,
  selectFileAndExportDataToExcel,
  udpateRowsDataRnValue,
} from './component/samplingProjectOverallService';
import { getSampleTableList } from './component/samplingRecordPopupService';
import {
  getSampleListTimes,
  getTypedSampleInfoIsIniValue,
  updateAllSampleType,
} from './component/samplingSampleListService';
import {
  getDataGridLoadSortFields,
  getRnColumn,
  getSampleSourceColumsOfExists,
  getSampleSourceFieldValues,
  getWhereSqlByFilterAnd,
  loadSampleSourceDataListOnly,
} from './component/samplingSourceService';
import {
  getAccountInfoList,
  getPageInfoByLoadOptions,
  getRealTableName,
  getSortFiedsCantSort,
} from './component/service';
import { consts } from './consts';
import { tempColumnsData } from './tableColumnData';
import { TableSampleDetail } from './tableSampleDetaill';
import { getErrorColumns, getTypedSampleInfoOfSampleTable } from './tableSamplingListService';
import { SampleField, SampleListTimes, SampleTable, TableSamplingRecordParams } from './typing';

const TableSamplingRecord = () => {
  const devGridRef = useRef<any>(null);
  //const [dataGridData, setDataGridData] = useState<any[]>([]);

  const searchTextBoxRef = useRef<any>(null);

  const dataParamsRef = useRef<any>(null);

  //当前查询数据的参数(导出时用到)
  //const [dataParams, setDataParams] = useState<any>();
  const { initialState } = useModel('@@initialState');
  const { dbname, sjnd } = initialState?.curPart as any;
  // const [pageIndex, setPageIndex] = useState<number>(0);
  // const [pageSize, setPageSize] = useState<number>(consts.defaultSampePageSize);
  const [dataSource, setDataSource] = useState<CustomStore | any[]>();
  const [params, setParams] = useState<TableSamplingRecordParams>({});

  //样本抽样次数
  const sampleListTimesRef = useRef<SampleListTimes[]>([]);
  const [searchValue, setSearchValue] = useState<string>();
  // const [sampleCount, setSampleCount] = useState<number>(0);

  const [loading, setLoading] = useState(false);

  //初始化
  useEffect(() => {
    // alert('这里要改加dataID')
    getSampleTableList(dbname, '%', undefined).then(async (sampleTableList) => {
      params.sampleTableList = [];
      const accountInfoList = await getAccountInfoList({ dbname });

      sampleTableList.forEach((sampleTable) => {
        if (params.sampleTableList) {
          if (sampleTable.isVoucher) {
            accountInfoList.forEach((accountInfo) => {
              if (params.sampleTableList) {
                params.sampleTableList.push({
                  ...sampleTable,
                  tableName: sampleTable.tableName.replace('{data_id}', accountInfo.Data_ID),
                  tableTitleDisplayText: `[${accountInfo.Data_ID}] ${sampleTable.tableTitle}`,
                });
              }
            });
          } else {
            params.sampleTableList.push({
              ...sampleTable,
              tableTitleDisplayText: `[${sampleTable.dataId}] ${sampleTable.tableTitle}`,
            });
          }
        }
      });
      if (sampleTableList.length) {
        params.curSampleTable = params.sampleTableList.find(
          (item) => item.isVoucher && item.tableName.endsWith(sjnd),
        );

        if (!params.curSampleTable) {
          params.curSampleTable = params.sampleTableList[0];
        }

        if (accountInfoList.length) {
          let dataId = accountInfoList[accountInfoList.length - 1].Data_ID;
          if (accountInfoList.some((item) => item.Data_ID === sjnd)) {
            dataId = sjnd;
          }
          params.curDataId = dataId;
          params.accountInfoList = accountInfoList; //这个是要现查询的
        }
        await loadSampleSourceInfo(params.curSampleTable as any);
        refreshData();
        setParams({ ...params });
        //初始化值
      }
    });
  }, []);

  //刷新数据
  const refreshData = useCallback(
    async (inSearchValue?: string) => {
      inSearchValue = inSearchValue ?? searchValue; //样本抽样次数
      //每次刷新都请求会慢,但下拉框下拉时请求,下拉框就会切换不了
      //sampleListTimesRef.current = await getSampleListTimes(dbname, params.curSampleTable, params.curDataId)
      loadSampleSourceDataList(
        params.curSampleTable,
        params.curSampleTable?.sampleAllFieldsArray,
        params.curDataId,
        inSearchValue,
      );
    },
    [params],
  );

  //加载样本源信息,不能用数据库请求,否则会切换不了
  async function loadSampleSourceInfo(sampleTable: SampleTable) {
    const sampleSourceFields = sampleTable.sampleAllFieldsArray; // await getSampleSourceFields(dbname, sampleTable.tableName);
    const textFieldsArray = sampleTable.sampleTextFieldsArray;
    const columns: any[] = [];
    columns.push(getRnColumn());
    columns.push(...getSampleTypeColumns());
    columns.push(...getSampleSourceColumsOfExists(sampleTable, sampleSourceFields, false));

    //错报字段: 默认在抽样次数后面增加
    let lastIndex = columns.findIndex((item) => item.dataField === 'sampleFrequency');
    if (textFieldsArray.length) {
      //如果有文本字段,在文本字段后面
      lastIndex = columns.findIndex(
        (item) => item.dataField === textFieldsArray[textFieldsArray.length - 1],
      );
    }
    columns.splice(lastIndex + 1, 0, ...getErrorColumns());

    params.columns = columns;
    setParams({ ...params });

    setLoading(true);
    sampleListTimesRef.current = await getSampleListTimes(
      dbname,
      params.curSampleTable,
      params.curDataId,
    );
    setLoading(false);
  }

  /**
   * 加载数据
   */
  const loadSampleSourceDataList = useCallback(
    async (
      sampleTable?: SampleTable,
      sampleSourceFields?: SampleField[],
      dataId?: string,
      inSearchValue?: string,
    ) => {
      // setLoading(true)
      if (!sampleTable?.tableName) return;
      //如果是初始值,要加载 typedSampleInfo
      if (getTypedSampleInfoIsIniValue(sampleTable.typedSampleInfo)) {
        sampleTable.typedSampleInfo = await getTypedSampleInfoOfSampleTable(dbname, sampleTable);
      }

      let whereSql = ' and IsChecked=1'; //已抽样本

      if (inSearchValue) {
        whereSql += ` and (1=0 `;
        sampleTable.sampleAllFieldsArray
          .filter((item) => item.fieldName.toLowerCase() != 'data_id' && !item.isNum)
          .forEach((item, index) => {
            if (index < 10) {
              //最多前面5个字段
              whereSql += ` or [${item.fieldName}] like '%${inSearchValue}%'`;
            }
          });
        whereSql += `)`;
      }

      const dataParams = {
        dbname,
        tableName: getRealTableName(sampleTable?.tableName, { data_id: dataId || '' }), //todo:要替换真值
        sortFields: sampleTable.sortFieldsArray.map((item) => `[${item}]`).join(','),
        fields: sampleSourceFields
          ? sampleSourceFields.map((item) => `[${item.fieldName}]`).join(',')
          : '',

        whereSql: whereSql || '',
      };
      dataParamsRef.current = dataParams;
      //数据参数
      //  setDataParams(dataParams);

      /*  const retData = await getApiData('sample.getSampleSourceDataList', dataParams);

         if (!retData.ok) {
             showNotDataMsg(retData.data)
             //msgError(retData.data);
             setLoading(false);
             return []
         }

         //更新数据行号
         udpateRowsDataRnValue(retData.data, pageIndex, pageSize, sampleSourceFields)

         if (sampleTable.typedSampleInfo) {
             updateAllSampleType(sampleTable.typedSampleInfo, retData.data,
                 sampleTable.sampleTextFieldsArray, sampleListTimesRef.current)
         }
         const totalCount = (retData.data.length ? retData.data[0].tc : 0);
         //所有行的数据,都给复制param,在TableSampleDetail中使到
         retData.data.forEach((item: any) => item.parentParams = {
             ...params,
             dataId, curSampleTable: sampleTable
         })
  */
      //focusedRowEnabled={true} 这个属性不能加,会导致数组分页的totalCount不生效
      setDataSource(
        new CustomStore({
          key: 'rn',
          load: async (loadOptions: LoadOptions) => {
            const { pageIndex, pageSize } = getPageInfoByLoadOptions(loadOptions);
            let rowsData: any[] = [];
            let filterWhereSql = getWhereSqlByFilterAnd(loadOptions.filter);
            console.log('loadOptions.filter', loadOptions.filter);
            console.log('filterWhereSql', filterWhereSql);
            const dataField = (loadOptions as any).dataField;

            //点击表头的过滤器时,只查询
            if (dataField) {
              rowsData = await getSampleSourceFieldValues(
                dbname,
                sampleTable,
                dataField,
                dataId,
                whereSql + filterWhereSql,
              );
              return { data: rowsData, totalCount: rowsData.length };
            } else {
              //正常查询数据时

              const sortFields = loadOptions.sort
                ? getDataGridLoadSortFields(loadOptions)
                : dataParams.sortFields;

              if (getSortFiedsCantSort(sortFields)) {
                msgError('此列不能排序!');
                devGridRef.current.instance.clearSorting();
                rowsData = devGridRef.current.instance.getDataSource()._items; //取原来的数据行
              } else {
                rowsData = await loadSampleSourceDataListOnly(
                  dbname,
                  sampleTable,
                  pageIndex,
                  pageSize,
                  sampleSourceFields,
                  sortFields,
                  dataId,
                  whereSql + filterWhereSql,
                );

                rowsData.forEach(
                  (item: any) =>
                    (item.parentParams = {
                      ...params,
                      dataId,
                      curSampleTable: sampleTable,
                    }),
                );
                //更新数据行号
                udpateRowsDataRnValue(rowsData, pageIndex, pageSize, sampleSourceFields);

                if (sampleTable.typedSampleInfo) {
                  updateAllSampleType(
                    sampleTable.typedSampleInfo,
                    rowsData,
                    sampleTable.sampleTextFieldsArray,
                    sampleListTimesRef.current,
                  );
                }
              }
              let retData2 = {
                data: rowsData,
                totalCount: rowsData.length ? rowsData[0].tc : 0,
              };
              updateSampleCount(retData2.totalCount);
              return retData2;
            }
            /*

                let retData2 = {
                    data: retData.data,
                    totalCount: totalCount
                }
                return retData2;
                */
          },
        }),
      );
      // setSampleCount(totalCount)
      //   setLoading(false);
      //   return retData.data;
    },
    [params.curSampleTable, params.curDataId],
  );

  const onBeforeExportData = (retDataInfo: { rowsData: any[]; totalCount: number }) => {
    //更新数据行号
    udpateRowsDataRnValue(
      retDataInfo.rowsData,
      0,
      consts.maxExportCount,
      params.curSampleTable?.sampleAllFieldsArray || [],
    );
    retDataInfo.rowsData.forEach((item, index) => (item.rn = index + 1)); //序号
    if (params.curSampleTable?.typedSampleInfo) {
      updateAllSampleType(
        params.curSampleTable.typedSampleInfo,
        retDataInfo.rowsData,
        params.curSampleTable.sampleTextFieldsArray,
        sampleListTimesRef.current,
      );
    }
  };

  function updateSampleCount(sampleCount: number) {
    const sampleCount_div = document.getElementById('tableSampleList_sampleCount_div');
    if (sampleCount_div) {
      sampleCount_div.innerText = `${sampleCount}`;
    }
  }
  //sql条件参数u

  const sampleListDataGrid = useMemo(() => {
    // console.log(tempColumnsData, devBox, tableYearArr, dataGridData, '@@@');
    if (tempColumnsData?.length > 0)
      return (
        <div className={`componentTableListBox`} key={'tableData'}>
          <DevGrid.MultipleTap
            id="tableSamplingListMaster"
            className={` PaperDevSortableGrid devHeadersCenter `}
            height={'100%'}
            width="100%"
            ref={devGridRef}
            isRemote={true}
            dataSource={dataSource}
            keyExpr="rn"
            columns={params.columns}
            showBorders={true}
            showRowLines={true}
            showColumnLines={true}
            allowColumnResizing={true}
            loadPanel={{ enabled: true }}
            columnMinWidth={30}
            defaultFocusedRowIndex={0}
            searchPanel={{ visible: false, width: 100 }}
            headerFilter={{
              width: 300,
              // height: window.innerHeight / 2,
              allowSearch: true,
              visible: true,
              texts: { ok: '确定' },
            }}
            sorting={{ mode: 'multiple' }} //shift多排序
            disableFirstHeaderSearch={true}
            pager={getGridDefaultPageProps()}
            //focusedRowEnabled={true} 这个属性不能加,会导致数组分页的totalCount不生效
            remoteOperations={{ paging: true, filtering: true, sorting: true }} //加这个才能支持远程分页 远程过滤 20230507
            // editing={{ mode: 'cell', allowUpdating: true }}
            renderAsync={true}
            sheetName={
              replaceInvalidFileName(
                params.curSampleTable?.tableTitleDisplayText ||
                  params.curSampleTable?.tableTitle ||
                  '',
              ) + '-样本数据'
            }
            excelName={
              replaceInvalidFileName(
                params.curSampleTable?.tableTitleDisplayText ||
                  params.curSampleTable?.tableTitle ||
                  '',
              ) +
              '-样本数据' +
              '-' +
              formatDateYYMMDD(new Date())
            }
            selection={{ mode: 'none' }}
            loadAllDevGridExport={async () => {
              //全部导出时的数据源
              setLoading(true);
              const rowsData: any = await getExportGridDataSource(
                dataParamsRef.current,
                onBeforeExportData,
              );
              setLoading(false);
              return { dataSource: rowsData };
            }}
            onContentReady={(e) => {
              /*  const rowsData: any[] = e.component.instance().getDataSource()?._items;
                     if (rowsData) {
                         setSampleCount(rowsData.length ? rowsData[0].tc : 0);
                     }
  */
            }}
          >
            <Paging enabled={true} defaultPageSize={consts.defaultSampePageSize} />
            <Toolbar>
              {/* <Item location='before' key="accountInfoList">
                        <div style={{ marginLeft: 10, display: 'flex', alignItems: 'center' }} >
                            <div>年度：</div>

                            <SelectBox
                                style={{ zIndex: 1 }}
                                width={80}

                                dataSource={params.accountInfoList}
                                displayExpr='Data_ID' //displayName
                                valueExpr='Data_ID'
                                value={params.curDataId}
                                hint={params.accountInfoList?.find(item => item.Data_ID == params.curDataId)?.displayName}

                                onValueChanged={async (e: any) => {
                                    params.curDataId = e.value;
                                    setParams({ ...params }) //立即更新状态,否则后续的执行不了
                                    if (params.curSampleTable) {
                                        await loadSampleSourceInfo(params.curSampleTable)
                                    }
                                    refreshData('');//加载数据
                                }}
                            />
                        </div>
                    </Item> */}
              <Item location="before" key="sampleSourceList">
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <div>样本源：</div>
                  <SelectBox
                    width={250}
                    placeholder="请选择样本源"
                    dataSource={params.sampleTableList}
                    dropDownOptions={{ width: 300 }}
                    searchEnabled={true}
                    displayExpr="tableTitleDisplayText"
                    valueExpr="tableName"
                    hint={params.curSampleTable?.tableTitle}
                    value={params.curSampleTable?.tableName}
                    onValueChanged={async (e: any) => {
                      const sampleTable = params.sampleTableList?.find(
                        (item) => item.tableName == e.value,
                      );
                      if (sampleTable) {
                        params.curSampleTable = sampleTable;
                        setParams({ ...params }); //立即更新状态,否则后续的执行不了

                        setSearchValue('');
                        await loadSampleSourceInfo(sampleTable);
                        //切换时,条件要删除
                        refreshData(''); //加载数据
                      }
                    }}
                  />
                </div>
              </Item>
              <Item location="before" key="sampleCount" locateInMenu={'auto'}>
                <div style={{ color: getCpasPrimaryColor() }}>
                  样本数量：<span id="tableSampleList_sampleCount_div"></span>
                </div>
              </Item>
              <Item location="after">
                <Button
                  text="导出"
                  hint="导出全部样本数据"
                  type="default"
                  className="for-button-padding5"
                  onClick={async () => {
                    setLoading(true);
                    let exportFileNameOnly =
                      replaceInvalidFileName(
                        params.curSampleTable?.tableTitleDisplayText ||
                          params.curSampleTable?.tableTitle ||
                          '',
                      ) + '-样本数据';
                    exportFileNameOnly = exportFileNameOnly.replace(/[\\\/:*?"<>|]/g, '');
                    exportFileNameOnly = exportFileNameOnly + '-' + formatDateYYMMDD(new Date());
                    await selectFileAndExportDataToExcel(
                      params.columns || [],
                      dataParamsRef.current,
                      exportFileNameOnly,
                      onBeforeExportData,
                    );

                    setLoading(false);
                  }}
                >
                  <CpasIcon type="icon-a-XLSXXLS" />
                  <span style={{ marginLeft: 10 }}>导出</span>
                </Button>
              </Item>

              <Item
                location="after"
                widget="dxTextBox"
                options={{
                  onInitialized: (e: any) => {
                    searchTextBoxRef.current = e.component;
                  },
                  text: searchValue,
                  width: 130,
                  hint: '输入关键字搜索',
                  mode: 'search',
                  placeholder: '',
                  onValueChanged: (e: any) => {
                    setSearchValue(e.value);
                  },
                  onFocusOut: (e: any) => {
                    const value = e.component._$textEditorInputContainer[0].childNodes[1].value;
                    setSearchValue(value);
                  },
                  onEnterKey: (e: any) => {
                    const value = e.component._$textEditorInputContainer[0].childNodes[1].value;
                    setSearchValue(value);
                    refreshData(value);
                    setTimeout(() => {
                      searchTextBoxRef.current?.focus();
                    }, 500);
                  },
                }}
              />
              <Item location="after">
                <Button
                  icon="iconfont icon-refresh"
                  className="refreshButton_Style"
                  onClick={() => {
                    refreshData(searchValue); //刷新
                  }}
                />
              </Item>
            </Toolbar>
            <MasterDetail enabled={true} component={TableSampleDetail} />
          </DevGrid.MultipleTap>
        </div>
      );
    return <div> </div>;
  }, [params, dataSource]);

  return (
    <div id="tableSamplingListMainDiv" style={{ height: '90vh' }}>
      {sampleListDataGrid}

      <LoadPanel visible={loading} />
    </div>
  );
};

export default TableSamplingRecord;
